<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="说明：Java Generic 泛型。">
<meta name="keywords" content="Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Generic 泛型">
<meta property="og:url" content="http://bebetter.site/2017/09/01/Language/Java-advanced/Generic 泛型/index.html">
<meta property="og:site_name" content="gatewayzy">
<meta property="og:description" content="说明：Java Generic 泛型。">
<meta property="og:updated_time" content="2017-09-01T05:58:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Generic 泛型">
<meta name="twitter:description" content="说明：Java Generic 泛型。">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"right","display":"always"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://bebetter.site/2017/09/01/Language/Java-advanced/Generic 泛型/"/>

  <title> Generic 泛型 | gatewayzy </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">gatewayzy</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">blog of gatewayzy</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Generic 泛型
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2017-09-01T13:58:10+08:00" content="2017-09-01">
              2017-09-01
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/Language/" itemprop="url" rel="index">
                    <span itemprop="name">Language</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><strong>说明：</strong>Java Generic 泛型。<br><a id="more"></a></p>
<p>参考文章：</p>
<h2 id="Generic-泛型"><a href="#Generic-泛型" class="headerlink" title="Generic 泛型"></a>Generic 泛型</h2><h3 id="泛型说明"><a href="#泛型说明" class="headerlink" title="泛型说明"></a>泛型说明</h3><ul>
<li>泛型Generic从jdk1.5出现。泛型有泛型方法、泛型类（泛型接口）。泛型常用于框架、库的设计中。</li>
<li>泛型本质上是参数化类型，类型是任意的，是经过传递的类型参数。但是不能传递基本类型，只能传递引用类型，但是基本数据会自动装箱为包装类型。</li>
<li>参数泛型的种类<ul>
<li>自定义泛型 <code>&lt;T&gt;</code> 用字母表示如T，V，T1等表示自定义泛型。</li>
<li>通配符泛型 <code>&lt;?&gt;</code> 用?表示通配符泛型。</li>
<li>？和T都表示不确定的类型，但是？不能用于之后的代码，常用于类型限定；而T可以在函数中使用和实例化等操作。</li>
</ul>
</li>
<li>类型限定<ul>
<li>? extends E ： 接收E类型或者E的子类型。<ul>
<li>使用extends向下泛型，可以<code>&lt;? extends E&gt;</code>或者<code>&lt;T extends E&gt;</code>，因为向下泛型可以对应到一个E的一个子类，所以编译可以使用E的类型进行编译。</li>
</ul>
</li>
<li>? super E ： 接收E类型或者E的父类型。<ul>
<li>使用supe进行向上泛型(向父类泛型)，那么前面只能用通配符?，不能用一个具体泛型T，因为一个类的父类可能直接只有Object类，也因此super的T只能用Object类进行编译。</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="泛型示例"><a href="#泛型示例" class="headerlink" title="泛型示例"></a>泛型示例</h3><ul>
<li>jdk8源码中List等都是使用了泛型。<ul>
<li>泛型接口、泛型类：声明规则是在类名后面添加一个类型参数，如 class Apple<t>，类内部就可以直接用T作为类型。</t></li>
<li>泛型方法：返回值之前写泛型参数，参数列表里面使用泛型</li>
<li><ul>
<li>泛型方法举例 <code>public static  &lt;T extends Number, S&gt; T[] toArray(T[] a)</code></li>
</ul>
</li>
</ul>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div></pre></td><td class="code"><pre><div class="line">public interface List&lt;E&gt; extends Collection&lt;E&gt; &#123;  // 泛型接口</div><div class="line">    int size();</div><div class="line">    Iterator&lt;E&gt; iterator();</div><div class="line"></div><div class="line">    &lt;T&gt; T[] toArray(T[] a);  // 接口内的public abstract toArray方法，加入新的泛型，由实现类实现</div><div class="line"></div><div class="line">    default void sort(Comparator&lt;? super E&gt; c) &#123;  // jdk8中接口的default方法，可以直接使用E，不需要引入新的泛型</div><div class="line">        Object[] a = this.toArray();</div><div class="line">        Arrays.sort(a, (Comparator) c);</div><div class="line">        ListIterator&lt;E&gt; i = this.listIterator();</div><div class="line">        for (Object e : a) &#123;</div><div class="line">            i.next();</div><div class="line">            i.set((E) e);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line">// 泛型类</div><div class="line">public class ArrayList&lt;E&gt; extends AbstractList&lt;E&gt;</div><div class="line">        implements List&lt;E&gt;, RandomAccess, Cloneable, java.io.Serializable&#123; </div><div class="line">    public int size() &#123; return size; &#125;</div><div class="line">    public Iterator&lt;E&gt; iterator() &#123; return new Itr(); &#125;</div><div class="line"></div><div class="line">    public &lt;T&gt; T[] toArray(T[] a) &#123;    // 典型的泛型接口的写法：返回值之前写泛型参数，参数列表里面使用泛型</div><div class="line">        if (a.length &lt; size)</div><div class="line">            // Make a new array of a&apos;s runtime type, but my contents:</div><div class="line">            return (T[]) Arrays.copyOf(elementData, size, a.getClass());</div><div class="line">        System.arraycopy(elementData, 0, a, 0, size);</div><div class="line">        if (a.length &gt; size)</div><div class="line">            a[size] = null;</div><div class="line">        return a;</div><div class="line">    &#125;</div><div class="line"></div><div class="line">&#125;</div><div class="line"></div><div class="line"></div><div class="line">Class Main&#123;</div><div class="line">    public static &lt;T&gt; void test(T t) &#123;</div><div class="line">        List&lt;String&gt; list1 = new ArrayList&lt;&gt;();  // 后面的参数默认是前面，否则编译错误</div><div class="line">        List&lt;String&gt; list2 = new ArrayList&lt;String&gt;();</div><div class="line">        List&lt;T&gt; tList = new ArrayList&lt;&gt;();</div><div class="line">        tList.add(t); </div><div class="line">    &#125; </div><div class="line">&#125;</div></pre></td></tr></table></figure>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag">#Java</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/09/01/Language/Java-advanced/Java 集合框架/" rel="next" title="Java 集合框架">
                <i class="fa fa-chevron-left"></i> Java 集合框架
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/09/01/Language/Java-advanced/Java 网络编程/" rel="prev" title="Java 网络编程">
                Java 网络编程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    


  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/statics/images/avatar.png"
               alt="gatewayzy" />
          <p class="site-author-name" itemprop="name">gatewayzy</p>
          <p class="site-description motion-element" itemprop="description">blog website with hexo and github pages</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">70</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">10</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">38</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="https://github.com/gatewayzy" title="Github-gatewayzy" target="_blank">Github-gatewayzy</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://google.com/" title="Goolge" target="_blank">Goolge</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://wiki.jikexueyuan.com/" title="Wiki-jike" target="_blank">Wiki-jike</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Generic-泛型"><span class="nav-number">1.</span> <span class="nav-text">Generic 泛型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#泛型说明"><span class="nav-number">1.1.</span> <span class="nav-text">泛型说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#泛型示例"><span class="nav-number">1.2.</span> <span class="nav-text">泛型示例</span></a></li></ol></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">gatewayzy</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  



  




  
  

  
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
  </script>

  <script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for (i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  </script>
  <script type="text/javascript" src="//cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>



  

  
<script type="text/javascript" async src="//push.zhanzhang.baidu.com/push.js">
</script>


</body>
</html>
